import time


class MyServer(object):
    def __init__(self,ip,port):
        import socket
        self.socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.socket.bind((ip,port))
        self.socket.listen(128)

    def run_test(self):
        while True:
            client_socket, client_addr = self.socket.accept()
            data = client_socket.recv(1024).decode('gbk')
            time.sleep(0.3)
            if data != '':
                print('接收到{}的数据{}'.format(client_addr[0],data))
                time.sleep(0.3)
                data=''
                if data == '1':#开灯
                    response_body = 'a'
                    #self.socket.bind(('192.168.43.4', 9090))
                    #self.socket.send('a'.encode('gbk'))
                    print('灯已打开')
                elif data == '0':#关灯
                    print('灯已关闭')
                else :
                    print('信息格式不对 无响应')
            # else:
            #     print('数据为空')

            response_body = ' 等待'

            response_header = 'HTTP/1.1 200 OK\n'
            response_header += 'content-type:text/html;charset=gbk\n'
            response_header += '\n'

            # 响应
            response = response_header + response_body
            # 发送给客户端
            client_socket.send(response.encode('gbk'))
            time.sleep(0.3)
            print('发送了',response.encode('gbk'))
            #print('接收到{}的数据{}'.format(client_addr[0], data))


server=MyServer('192.168.43.61',9090)
server.run_test()